<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton } from 'element-plus'
// import * as XLSX from 'xlsx'
import { Table } from '@/components/Table'
// import { spForageListApi } from '@/api/sp/food'
import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { useTable } from '@/hooks/web/useTableTest'
import { reactive, ref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import { dbForageSpecsListApi, dbForageSpecsexportApi } from '@/api/forms'
import { ucUserListAdminApi } from '@/api/uc/user'

import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const exportClick = async () => {
  dialogTableVisible.value = true
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa)
  let res: any = await dbForageSpecsListApi({
    create_time: aaa.create_time,
    forage_name: aaa.forage_name,
    name: aaa.name,
    pasture_org_id: aaa.pasture_org_id,
    update_user_id: aaa.update_user_id
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    // window.open(data.url)
    console.log(res.count, Math.ceil(res.count / 10000))
    FormsNumber.value = Math.ceil(res.count / 10000)
  }
  // pageNo.value = 1
  // await getSeeList()
  // let arr = exportData.value.map((item) => {
  //   // item.state = getDictLabel('org_state', item.state)
  //   // item.org_type = getDictLabel('org_type', item.org_type)
  //   // item.is_stop = getDictLabel('is_stop', item.is_stop)
  //   return {
  //     所属牧场: item.pasture_org_name,
  //     饲料名称: item.name,
  //     单位: item.unit,
  //     包装规格: item.sku,
  //     饲料备注: item.note,
  //     创建人: item.create_user_name,
  //     创建日期: item.create_time
  //     // 锁定库存: item.lock_stock,
  //     // 总库存: item.total_stock,
  //     // 可用库存: item.available_stock,
  //     // 所有者: item.owner_user_name,
  //     // 所有者角色: item.owner_sys_role_name,
  //     // 创建人: item.create_user_name,
  //     // 创建日期: item.create_time,
  //     // 修改人: item.update_user_name,
  //     // 修改时间: item.update_time
  //   }
  // })
  // let sheet = XLSX.utils.json_to_sheet(arr)
  // let book = XLSX.utils.book_new()

  // sheet['!cols'] = [{ wch: 100 }, { wch: 30 }, { wch: 25 }]

  // XLSX.utils.book_append_sheet(book, sheet, 'sheet1')
  // XLSX.writeFile(book, '饲料信息列表.xls')
  // ElMessage.warning('开发中，稍后查看')
}
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: dbForageSpecsListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { setSearchParams } = methods

// getList()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 120,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    width: 150,
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListAdminApi,
        response: { count: 'count', data: 'data' },
        title: '选择创建人（双击选择）',
        nameField: 'pasture_org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        crudSchemas: [
          { field: 'org_name', label: '牧场名称', search: { show: true } }
          // { field: 'org_id', label: '牧场ID', search: { show: true } }
        ]
      },
      show: true
    },
    table: {
      show: false
    }
  },
  {
    field: 'forage_name',
    label: '饲料名称',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'name',
    label: '饲料规格',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'number',
    label: '换算基础单位的数量',
    width: 180,
    search: {
      show: false
    }
  },
  {
    field: 'unit',
    label: '单位',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return cellValue != '0' ? getDictLabel('unit', cellValue) : ' '
    },
    search: {
      show: false
    }
  },
  {
    field: 'total_stock',
    label: '总库存',
    search: {
      show: false
    }
  },
  {
    field: 'lock_stock',
    label: '锁定库存',
    width: 120,
    search: {
      show: false
    }
  },
  {
    field: 'available_stock',
    label: '可用库存',
    width: 120,
    search: {
      show: false
    }
  },
  {
    field: 'update_user_id',
    label: '创建人',
    width: 80,
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: ucUserListAdminApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择创建人（双击选择）',
        nameField: 'user_name',
        relNameField: 'nickname',
        valueField: 'user_id',
        crudSchemas: [
          {
            field: 'nickname',
            label: '姓名',
            search: {
              show: true
            }
          },
          {
            field: 'username',
            label: '用户名',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '饲料备注',
    search: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)

const Export = async (index) => {
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa)
  let { data }: any = await dbForageSpecsexportApi({
    create_time: aaa.create_time,
    forage_name: aaa.forage_name,
    name: aaa.name,
    pasture_org_id: aaa.pasture_org_id,
    update_user_id: aaa.update_user_id,
    pageNo: index,
    pageSize: 10000
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)

    // console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px w-[100%] flex justify-end" v-show="tableObject.paramsObj.params">
      <ElButton type="primary" @click="exportClick()"> 导出EXCEL </ElButton>
    </div>
    <Table
      v-show="tableObject.paramsObj.params"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      :selection="false"
      @register="register"
    />
  </ContentWrap>

  <el-dialog v-model="dialogTableVisible" title="饲料主档导出详情">
    <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
      <span style="margin: 20px">饲料主档 - {{ item }}</span>
      <ElButton type="primary" @click="Export(item)">导出</ElButton>
    </div>
  </el-dialog>
</template>
